package com.kehutong.contact.admin;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.kehutong.contact.enums.HouseType;
import com.kehutong.contact.service.DataPvService;
import org.apache.xmlbeans.impl.regex.REUtil;
import org.coraframework.authz.HasPermission;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.EnumUtil;
import org.coraframework.util.Objects;

import com.kehutong.common.DoveClient;
import com.kehutong.common.util.Token;
import com.kehutong.contact.entity.ResidentHouseBindApply;
import com.kehutong.contact.enums.AuditStatus;
import com.kehutong.contact.service.impl.ResidentHouseBindApplyService;

/**
 * 微信房屋绑定申请控制器
 *
 * @author: liukunlong
 * @date: 2021-04-03 15:32
 */
@MvcAction
@ReqMapping("/admin/crm/weChatHouseBindApply")
public class ResidentHouseBindApplyController {
    static final Logger logger = LoggerFactory.getLogger(ResidentHouseBindApplyController.class);
    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private ResidentHouseBindApplyService weChatHouseBindApplyService;


    @Inject
    private DoveClient doveClient;


    @Inject
    private DataPvService dataPvService;

    /**
     * 根据条件微信房屋绑定申请列表
     *
     * @param jsonObject 查询条件
     * @return 微信房屋绑定申请列表
     * @throws Exception 异常
     */
    @HasPermission("crm:resident:house:bind:apply:view")
    @ReqMapping("/list")
    public Object getResidentHouseBindApplyList(Token token, JSONObject jsonObject) throws Exception {
        Page<ResidentHouseBindApply> result = null;
        //构建数据权限
        dataPvService.buildUserDataPv(token,jsonObject);
        FindPage<ResidentHouseBindApply> find = jdbcSession.findPage(ResidentHouseBindApply.class)
                .eq(jsonObject, "id","mobile", "status", "auditNo", "houseNo", "type","houseType","communityNo")
                .like(jsonObject, "realname","communityName")
                .eq("deleted", 0)
                .between("createTime", jsonObject, "createTime", "createTime")
                .between("auditTime", jsonObject, "auditTime", "auditTime")
                .order("createTime", "desc")
                .page(jsonObject);
        String search = jsonObject.getString("search");
        if(Objects.nonEmpty(search)){
            find.markBegin();
            find.like("id", search).or();
            find.like("realname", search).or();
            find.like("mobile", search).or();
            find.markEnd();
        }
        result = find.exe();
        //构建管家信息
        if (Objects.nonNull(result)) {
            List<ResidentHouseBindApply> residentHouseBindApplyList = result.getList();
            for (ResidentHouseBindApply residentHouseBindApply : residentHouseBindApplyList) {
                buildEmployee(residentHouseBindApply);
            }
        }
        return result;
    }

    public Map<String,JSONObject> getEmployeeMap(List<String> employeeIds) throws Exception {
        JSONObject result = doveClient.post("/basic/employee/service/list", http->{
            JSONObject body = new JSONObject();
            body.put("id", employeeIds);
            body.put("pageNo", 1);
            body.put("pageSize", 1000000);
            http.setBody(body.toString());
        });

        JSONArray data = result.getJSONObject("data").getJSONArray("list");

        if (Objects.isNull(data)) {
            return null;
        }

        Map<String,JSONObject> employeeMap = new HashMap<>();
        data.forEach(item->{
            JSONObject obj = (JSONObject) item;
            employeeMap.put(obj.getString("id"), obj);
        });

        return employeeMap;
    }

    /**
     * 构建管家信息
     * @param residentHouseBindApply 住户房屋申请对象
     */
    public void buildEmployee(ResidentHouseBindApply residentHouseBindApply) throws Exception{
        JSONObject buildingResult=new JSONObject();
        HouseType houseType=residentHouseBindApply.getHouseType();
        if(Objects.equal(HouseType.HOUSE.getId(),houseType.getId())){
            buildingResult=doveClient.post("/basic/building/service/get", (http) -> {
                JSONObject body = new JSONObject();
                body.put("id",residentHouseBindApply.getBuildNo());
                http.setBody(body.toJSONString());
            });
        }else if(Objects.equal(HouseType.SHOP.getId(),houseType.getId())){
            buildingResult=doveClient.post("/basic/shop/classify/service/get", (http) -> {
                JSONObject body = new JSONObject();
                body.put("id",residentHouseBindApply.getBuildNo());
                http.setBody(body.toJSONString());
            });
        }else if(Objects.equal(HouseType.PARKING.getId(),houseType.getId())){
            buildingResult=doveClient.post("/basic/parking/classify/service/get", (http) -> {
                JSONObject body = new JSONObject();
                body.put("id",residentHouseBindApply.getBuildNo());
                http.setBody(body.toJSONString());
            });
        }

        if (buildingResult.getIntValue("code")== 200) {
            JSONObject buildingJson=buildingResult.getJSONObject("data");
            if(Objects.nonNull(buildingJson)){
                List<String> employeeNos = JSONObject.parseArray(buildingJson.getJSONArray("employeeNos").toJSONString(),String.class);
                List<String> employeeNames = new ArrayList<>();
                if(Objects.nonEmpty(employeeNos)){
                    Set<String> employeeIds = new HashSet<>(employeeNos);
                    Map<String,JSONObject> employeeMap = getEmployeeMap(new ArrayList<>(employeeIds));
                    for (String employeeNo : employeeNos) {
                        JSONObject employee = employeeMap.get(employeeNo);
                        if(Objects.nonNull(employee)){
                            employeeNames.add(employee.getString("name"));
                        }
                    }
                }
                residentHouseBindApply.setEmployeeNos(employeeNos);
                residentHouseBindApply.setEmployeeNames(employeeNames);
            }
        }
    }


    /**
     * 根据表示获取微信房屋绑定申请对象
     *
     * @param residentHouseBindApply 微信房屋绑定申请对象
     * @return 微信房屋绑定申请对象
     * @throws Exception 异常
     */
    @HasPermission("crm:resident:house:bind:apply:view")
    @ReqMapping("/get")
    public Object getResidentHouseBindApply(ResidentHouseBindApply residentHouseBindApply) throws Exception {
        buildEmployee(residentHouseBindApply);
        return residentHouseBindApply;
    }


    /**
     * 更新微信房屋绑定申请对象
     * todo 调用主库有问题
     *
     * @return 微信房屋绑定申请对象
     * @throws Exception
     */

    @HasPermission("crm:resident:house:bind:apply:edit")
    @Bean(copy = true)
    @ReqMapping("/update")
    public Object updateResidentHouseBindApply(Token token, JSONObject jsonObject) throws Exception {
        String id = jsonObject.getString("id");
        String auditRemarks = jsonObject.getString("auditRemarks");
        ResidentHouseBindApply dbResidentHouseBindApply = jdbcSession.findById(ResidentHouseBindApply.class, id);
        dbResidentHouseBindApply.setAuditNo(token.getUuid());
        dbResidentHouseBindApply.setAuditName(token.getUsername());
        dbResidentHouseBindApply.setAuditTime(LocalDateTime.now());
        dbResidentHouseBindApply.setAuditRemarks(auditRemarks);
        jdbcSession.updateById(dbResidentHouseBindApply);
        return Result.success();
    }

    /**
     * 审核微信房屋绑定申请
     * 1.审核通过增加客户通业主信息
     * 2.增加微信会员房屋绑定信息
     * 3.回写微信会员信息的手机号与真实姓名,并且设置微信会员绑定过会员
     *
     * @param token      用户信息
     * @param jsonObject 微信房屋绑定申请对象
     * @return 操作结果
     * @throws Exception 异常
     */
    @HasPermission("crm:resident:house:bind:apply:edit")
    @Bean(copy = true)
    @ReqMapping("/audit")
    public Object auditResidentHouseBindApply(Token token, JSONObject jsonObject) throws Exception {
        //TODO 自动切换数据库后需要重构
        String id = jsonObject.getString("id");
        String auditRemarks = jsonObject.getString("auditRemarks");
        JSONObject statusJson = jsonObject.getJSONObject("status");
        ResidentHouseBindApply dbResidentHouseBindApply = jdbcSession.findById(ResidentHouseBindApply.class, id);
        AuditStatus auditStatus = EnumUtil.getEnum(AuditStatus.class, statusJson.getString("id"));
        dbResidentHouseBindApply.setStatus(auditStatus);
        dbResidentHouseBindApply.setAuditNo(token.getUuid());
        dbResidentHouseBindApply.setAuditName(token.getUsername());
        dbResidentHouseBindApply.setAuditAvatar(token.getHeadUrl());
        dbResidentHouseBindApply.setAuditTime(LocalDateTime.now());
        dbResidentHouseBindApply.setAuditRemarks(auditRemarks);
        return weChatHouseBindApplyService.auditResidentHouseBindApply(dbResidentHouseBindApply);
    }



    /**
     * 审核微信房屋绑定申请
     * 1.审核通过增加客户通业主信息
     * 2.增加微信会员房屋绑定信息
     * 3.回写微信会员信息的手机号与真实姓名,并且设置微信会员绑定过会员
     *
     * @param token      用户信息
     * @param jsonObject 微信房屋绑定申请对象
     * @return 操作结果
     * @throws Exception 异常
     */
    @HasPermission("crm:resident:house:bind:apply:edit")
    @Bean(copy = true)
    @ReqMapping("/batch/audit")
    public Object batchAuditResidentHouseBindApply(Token token, JSONObject jsonObject) throws Exception {
        JSONArray auditList=jsonObject.getJSONArray("auditList");
        if (Objects.nonEmpty(auditList)) {
            for (Object auditObj : auditList) {
                JSONObject audit = (JSONObject) auditObj;
                String id = audit.getString("id");
                String auditRemarks = audit.getString("auditRemarks");
                JSONObject statusJson = audit.getJSONObject("status");
                ResidentHouseBindApply dbResidentHouseBindApply = jdbcSession.findById(ResidentHouseBindApply.class, id);
                AuditStatus auditStatus = EnumUtil.getEnum(AuditStatus.class, statusJson.getString("id"));
                dbResidentHouseBindApply.setStatus(auditStatus);
                dbResidentHouseBindApply.setAuditNo(token.getUuid());
                dbResidentHouseBindApply.setAuditName(token.getUsername());
                dbResidentHouseBindApply.setAuditAvatar(token.getHeadUrl());
                dbResidentHouseBindApply.setAuditTime(LocalDateTime.now());
                dbResidentHouseBindApply.setAuditRemarks(auditRemarks);
                weChatHouseBindApplyService.auditResidentHouseBindApply(dbResidentHouseBindApply);
            }
        }
        return Result.success();
    }


    /**
     * 删除微信房屋绑定申请
     *
     * @param weChatHouseBindApply 微信房屋绑定申请对象
     * @return 操作结果
     * @throws Exception 异常
     */
    @HasPermission("crm:resident:house:bind:apply:edit")
    @ReqMapping("/delete")
    public Object deleteResidentHouseBindApply(ResidentHouseBindApply weChatHouseBindApply) throws Exception {
        if (Objects.isNull(weChatHouseBindApply.getId())) {
            Result.error(1, "申请编号不能为空");
        }
        weChatHouseBindApply.setDeleted(true);
        jdbcSession.updateById(weChatHouseBindApply);
        return Result.success();
    }
}
